//
//  LiveNotesController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/31.
//

import UIKit
import SnapKit
import Reusable
import Localize_Swift

class LiveNotesController: BaseViewController {
    
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.backgroundColor = .clear
        // 滚动时隐藏键盘
        scrollView.keyboardDismissMode = .onDrag
        if #available(iOS 11.0, *) {
            scrollView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        view.addSubview(scrollView)
        return scrollView
    }()
    
    private lazy var submitButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("确认".localized(.call), for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.setBackgroundColor(.themeColor, for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        button.addTarget(self, action: #selector(submitAction), for: .touchUpInside)
        button.addRoundedCorners(radius: 22)
        return button
    }()
    
    /// 通话时长
    private lazy var durationView: CallNotesInfoView = {
        CallNotesInfoView.loadFromNib()
    }()
    
    /// 观看人数
    private lazy var peopleNumberView: CallNotesInfoView = {
        CallNotesInfoView.loadFromNib()
    }()
    
    /// 申请连麦人数
    private lazy var linkNumView: CallNotesInfoView = {
        CallNotesInfoView.loadFromNib()
    }()
    
    /// 申请视频通话信息人数
    private lazy var callNumView: CallNotesInfoView = {
        CallNotesInfoView.loadFromNib()
    }()
    
    private var roomId: String
    init(_ roomId: String) {
        self.roomId = roomId
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 统计接口调用次数
    private var count: Int = 0
    
    private var callNotesModel: CallNotesModel = CallNotesModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        initNav()
        initUI()
        updateLanguageAction()
        loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        vhl_interactivePopEnable = false
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        vhl_interactivePopEnable = true
    }
    
    override func updateLanguageAction() {
        
        navigationItem.title = "直播小记".localized(.live)
        submitButton.setTitle("确认".localized(.call), for: .normal)
        
        durationView.titleLabel.text = "直播时长".localized(.live)
        peopleNumberView.titleLabel.text = "观看人数".localized(.live)
        linkNumView.titleLabel.text = "申请连麦".localized(.live)
        callNumView.titleLabel.text = "申请视频通话信息".localized(.live)
    }
}


// MARK: - private
private extension LiveNotesController {
    
    func initNav() {
        // 设置初始导航栏透明度
        vhl_navBarBackgroundAlpha = 0
        navigationItem.title = "直播小记".localized(.live)
        // navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIView())
    }
    
    func initUI() {
        view.backgroundColor = UIColor(hex: "F7F7F7")
        
        view.addSubview(submitButton)
        submitButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(44)
            make.bottom.equalToSuperview().offset(-xIphoneBottomSafeHeight - 20)
        }
        
        
        scrollView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(xIphoneNavStatusBarHeight)
            make.bottom.equalTo(submitButton.snp.top).offset(-10)
            
        }
        
        scrollView.addSubview(durationView)
        durationView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview()
            make.width.equalTo(xScreenW - 16*2)
            make.height.equalTo(40)
        }
        
        scrollView.addSubview(peopleNumberView)
        peopleNumberView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalTo(durationView.snp.bottom).offset(16)
            make.width.equalTo(xScreenW - 16*2)
            make.height.equalTo(40)
        }
        
        scrollView.addSubview(linkNumView)
        linkNumView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalTo(peopleNumberView.snp.bottom).offset(16)
            make.width.equalTo(xScreenW - 16*2)
            make.height.equalTo(40)
        }
        
        scrollView.addSubview(callNumView)
        callNumView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalTo(linkNumView.snp.bottom).offset(16)
            make.width.equalTo(xScreenW - 16*2)
            make.height.equalTo(40)
        }
        
        view.layoutIfNeeded()
        scrollView.contentSize = CGSizeMake(xScreenW, CGRectGetMaxY(callNumView.frame) + 16)
    }
    
    func loadData() {
        let target = JavaAPI.callNotes(roomId: roomId)
        YLHUD.showLottie()
        YLRequest.request(target) { [self] result in
            switch result {
            case .success(let res):
                
                let dataDictionary = res.dataDictionary
                guard let model = JsonUtil.modelFromDictionary(dataDictionary, CallNotesModel.self) else {
                    YLHUD.showMessage(res.dataString)
                    return
                }
                if model.roomId.isEmpty {
                    DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1) {
                        self.count += 1
                        if self.count > 2 {
                            YLHUD.hideHUD()
                            self.back()
                            return
                        }
                        self.loadData()
                    }
                    return
                }
                YLHUD.hideHUD()
                callNotesModel = model
                if let translatorModel = callNotesModel.translatorList.first {
                    // 默认选中第一个翻译员
                    translatorModel.isSelected = true
                }
                showData(model: callNotesModel)
                
            case .failure(let err):
                YLHUD.showHint(.error, err.errMsg)
            }
        }
        
    }
    
    func showData(model: CallNotesModel) {
        durationView.contentLabel.text =  model.callDuration + "分钟".localized(.call)
        let duration = model.callDuration.sg.toInt
        if duration < 60 {
            durationView.contentLabel.text = String(duration) + "分钟".localized(.call)
            
        } else {
            let minutes = duration%60
            let hours = duration/60
            durationView.contentLabel.text = "时分".localizedFormat(arguments: String(hours), String(minutes), name: .call)
        }
        
        peopleNumberView.contentLabel.text = String(model.viewCount) + "人".localized(.call)
        linkNumView.contentLabel.text = String(model.applyCount) + "人".localized(.call)
        callNumView.contentLabel.text = String(model.reservationCount) + "人".localized(.call)
    }
    
}

// MARK: - 响应事件
private extension LiveNotesController {
    @objc func submitAction() {
        backAction()
    }
}
